package com.wwwarehouse.usercenter.fragment.businessunit;


import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.activity.map.MapActivity;
import com.wwwarehouse.common.activity.media.ClipImageActivity;
import com.wwwarehouse.common.activity.media.SelectImageActivity;
import com.wwwarehouse.common.bean.map.NearAddressBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.upload.FileUploadBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.SharedPreferencesHelper;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static android.app.Activity.RESULT_OK;

/**
 * Creator by zhenwang.xiang on 2017/8/14 13:20
 * Description: 创建顶级业务单位
 */

@Route(path = UserCenterConstant.PATH_CREATE_BUSINESSUNIT_FRAGMENT)
public class CreateBusinessUnitFragment extends BaseFragment implements View.OnClickListener, EasyPopupWindow.ChildClickListener, PermissionUtils.PermissionCallbacks {

    private View mRootView, PopItemView;
    private ImageView mImgHelp, mImgLogo;
    private ClearEditText mCompanyName;
    private ClearEditText mCompanyPhone;
    private TextInputLayout mNameLayout;
    private TextInputLayout mPhoneLayout;
    private LinearLayout mLlocation;
    private TextView mLocationAddress;
    private TextView mLocationDetialAddress;
    private FrameLayout mFlUploadLicense;
    private ImageView mImgUploadLincense;
    private LinearLayout mLlUploadLincense;
    private Button mBtnCreate;
    private LinearLayout mCreateLayout, mCreateFinashLayout;
    private TextView mTvShopName;
    private Button mBtnCreateSuccess;

    private static final int REQUEST_CREATE_BUSINESSUNIT_CODE = 0;
    private static final int REQUEST_MEDIA_SELECT_IMAGE = 1;
    private static final int REQUEST_MEDIA_SELECT_IMAGE_GALLERY = 2;
    private static final int REQUEST_UPLOAD_IMAGE_CAMERA = 3;
    private static final int REQUEST_UPLOAD_IMAGE_GALLERY = 4;
    private static final int MAPREQUEST_CODE = 5;

    private EasyPopupWindow mEasyPopupWindow;
    private EasyPopupWindow mSelectPhonePopupWindow;
    private File mFile;
    private FileUtils mFileUtils;
    private String[] camreaPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String[] takePhonePermission = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
    private String uploadUrl = "", imagePath = "";
    private String businessLicense = "", businessUnitIcon = "";
    private String area = "", businessUnitName = "", city = "", detailedAddress = "", latitudeLongitude = "", mobilePhone = "", province = "";
    SharedPreferencesHelper sp;
    private int phoneFlag = 0;
    private boolean isErrorName = false, isErrorPhone = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_create_business_unit, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        ((BaseActivity) mActivity).hideSoftByEditViewIds(new int[]{R.id.et_company_name, R.id.et_company_phone});
    }

    private void initView() {
        mImgHelp = $(R.id.img_help);
        mImgLogo = $(R.id.img_company_logo);
        mCompanyName = $(R.id.et_company_name);
        mCompanyPhone = $(R.id.et_company_phone);
        mNameLayout = $(R.id.name_input_layout);
        mPhoneLayout = $(R.id.phone_input_layout);
        mLlocation = $(R.id.ll_location);
        mLocationAddress = $(R.id.location_address);
        mLocationDetialAddress = $(R.id.location_detial_address);
        mFlUploadLicense = $(R.id.fl_upload);
        mImgUploadLincense = $(R.id.img_upload);
        mLlUploadLincense = $(R.id.ll_upload);
        mTvShopName = $(R.id.tv_shopname);
        mBtnCreate = $(R.id.btn_create);
        mBtnCreateSuccess = $(R.id.btn_create_success);
        mCreateLayout = $(R.id.ll_create);
        mCreateFinashLayout = $(R.id.ll_create_finish);

        sp = new SharedPreferencesHelper(getActivity());
        mFileUtils = new FileUtils();

        mImgHelp.setOnClickListener(this);
        mImgLogo.setOnClickListener(this);
        mBtnCreate.setOnClickListener(this);
        mBtnCreateSuccess.setOnClickListener(this);
        mFlUploadLicense.setOnClickListener(this);
        mLlocation.setOnClickListener(this);

        mCompanyName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                InputFilter filter = new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        LogUtils.showInfoLog(source.toString() + start + end);
                        if (dstart < 20) {
                            if (source.equals(" ")) {
                                return "";
                            } else {
                                return null;
                            }
                        } else {
                            return "";
                        }

                    }
                };
                mCompanyName.setFilters(new InputFilter[]{filter});
            }

            @Override
            public void afterTextChanged(Editable s) {
                String editable = mCompanyName.getText().toString().trim();
                int lenth = editable.length();
                if ((!checkNameMark(editable) || editable.length() > 20) && lenth > 0) {
                    isErrorName = true;
                    mNameLayout.setStateWrong(getString(R.string.usercenter_tips_name));
                    mBtnCreate.setEnabled(false);
                    mBtnCreate.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
                } else {
                    isErrorName = false;
                    mNameLayout.setStateNormal();
                }
                setButtonState();
            }
        });

        mCompanyName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isErrorName) {
                    mNameLayout.setStateWrong(getString(R.string.usercenter_tips_name));
                    if (hasFocus && isErrorName == false) {
                        mNameLayout.setStateNormal(getString(R.string.usercenter_tips_name));
                    }
                } else {
                    mNameLayout.setStateNormal(getString(R.string.usercenter_tips_name));
                    if (hasFocus) {
                        mNameLayout.setStateNormal(getString(R.string.usercenter_tips_name));
                    }
                }
            }
        });

        mCompanyPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isErrorPhone) {
                    mPhoneLayout.setStateWrong(getString(R.string.center_tips_phone));
                    if (hasFocus && isErrorPhone == false) {
                        mPhoneLayout.setStateNormal(getString(R.string.center_tips_phone));
                    }
                } else {
                    mPhoneLayout.setStateNormal(getString(R.string.center_tips_phone));
                    if (hasFocus) {
                        mPhoneLayout.setStateNormal(getString(R.string.center_tips_phone));
                    }
                }
            }
        });

        mCompanyPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String phone = mCompanyPhone.getText().toString().trim();
                if (phone.length() > 12 || phone.length() < 7 && phone.length() > 0) {
                    isErrorPhone = true;
                    mPhoneLayout.setStateWrong(getString(R.string.center_tips_phone));
                    mBtnCreate.setEnabled(false);
                    mBtnCreate.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
                } else {
                    isErrorPhone = false;
                    mPhoneLayout.setStateNormal();
                }
                setButtonState();
            }
        });

        mLocationDetialAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setButtonState();
            }
        });

        PopItemView = View.inflate(getActivity(), R.layout.pop_up_create_businessunit, null);

        mImgHelp.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                boolean isFirstOpen = sp.getBooleanValue("businessunit", true);
                if (isFirstOpen) {
                    mEasyPopupWindow = new EasyPopupWindow.Builder(getActivity())
                            .setView(PopItemView)
                            .setSize(ViewGroup.LayoutParams.WRAP_CONTENT, ConvertUtils.dip2px(getActivity(), 310))
                            .setOutsideTouchHide(true)
                            .setBackgroundAlpha(0.6f)
                            .create();

                    int loc[] = new int[2];
                    mImgHelp.getLocationOnScreen(loc);
                    mEasyPopupWindow.setAnimationStyle(R.style.pop_anim_by_create_businessunit);
                    mEasyPopupWindow.showAtLocation(mImgHelp, Gravity.RIGHT | Gravity.TOP, 34, loc[1] + mImgHelp.getHeight() + 20);
                    sp.putBooleanValue("businessunit", false);
                }
                mImgHelp.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

    }

    /**
     * 验证用户名只包含字母，数字，中文
     *
     * @param
     * @return
     */
    public static boolean checkNameMark(String name) {
        String all = "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$";
        Pattern pattern = Pattern.compile(all);
        return pattern.matches(all, name);
    }

    /**
     * Description: 判断是否显示按钮
     */
    private void setButtonState() {
        String name = mCompanyName.getText().toString().trim();
        String phone = mCompanyPhone.getText().toString().trim();
        String location = mLocationDetialAddress.getText().toString().trim();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(location) && isErrorPhone == false && isErrorName == false) {
            mBtnCreate.setEnabled(true);
            mBtnCreate.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        } else {
            mBtnCreate.setEnabled(false);
            mBtnCreate.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof CreateBusinessUnitFragment) {
            mActivity.setTitle(getString(R.string.create_company_info));
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onClick(View v) {
        if (mSelectPhonePopupWindow != null && mSelectPhonePopupWindow.isShowing()) {
            mSelectPhonePopupWindow.dismiss();
        }
        int id = v.getId();
        if (id == R.id.img_help) {
            mEasyPopupWindow = new EasyPopupWindow.Builder(getActivity())
                    .setView(PopItemView)
                    .setSize(ViewGroup.LayoutParams.WRAP_CONTENT, ConvertUtils.dip2px(getActivity(), 310))
                    .setOutsideTouchHide(true)
                    .create();
            int loc[] = new int[2];
            mImgHelp.getLocationOnScreen(loc);
            mEasyPopupWindow.setAnimationStyle(R.style.pop_anim_by_create_businessunit);
            mEasyPopupWindow.showAtLocation(mImgHelp, Gravity.RIGHT | Gravity.TOP, 34, loc[1] + mImgHelp.getHeight() + 20);
        } else if (id == R.id.img_company_logo) {
            phoneFlag = 1;
            PermissionUtils.requestPermissions(this, takePhonePermission, 2);
        } else if (id == R.id.btn_create) {
            businessUnitName = mCompanyName.getText().toString().trim();
            mobilePhone = mCompanyPhone.getText().toString().trim();
            Map<String, Object> map = new HashMap<>();
            map.put("cardUkid", null);
            map.put("type", "function");
            Map<String, String> itemmap = new HashMap<>();
            itemmap.put("area", area);
            itemmap.put("businessLicense", businessLicense);
            itemmap.put("businessUnitIcon", businessUnitIcon);
            itemmap.put("businessUnitName", businessUnitName);
            itemmap.put("city", city);
            itemmap.put("detailedAddress", detailedAddress);
            itemmap.put("latitudeLongitude", latitudeLongitude);
            itemmap.put("mobilePhone", mobilePhone);
            itemmap.put("province", province);
            map.put("businessUnitInfo", itemmap);
            NoHttpUtils.httpPost(UserCenterConstant.CREATE_BUSINESSUNIT, map, mOnResponseListener, REQUEST_CREATE_BUSINESSUNIT_CODE);
        } else if (id == R.id.btn_create_success) {
            popFragment();
        } else if (id == R.id.ll_location) {
            startActivityForResult(new Intent(getContext(), MapActivity.class), MAPREQUEST_CODE);
        } else if (id == R.id.fl_upload) {
            mSelectPhonePopupWindow = PopUpUtils.showPopUpBottom(R.layout.upload_image_popupwindow, getActivity(), mRootView, false, this);
        } else if (id == R.id.btn_take_photo) {
            Constant.isTakePhotoFinished = false;
            phoneFlag = 3;
            PermissionUtils.requestPermissions(this, camreaPermission, 1);
        } else if (id == R.id.btn_gallery) {
            phoneFlag = 2;
            PermissionUtils.requestPermissions(this, takePhonePermission, 2);
        } else if (id == R.id.btn_cancel) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Constant.isTakePhotoFinished = true;
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_CREATE_BUSINESSUNIT_CODE:
                    if ("0".equals(commonClass.getCode())) {
                        mCreateLayout.setVisibility(View.GONE);
                        mCreateFinashLayout.setVisibility(View.VISIBLE);
                        mTvShopName.setText(mCompanyName.getText().toString().trim());
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
        }

        @Override
        public void onFinish(int what) {
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_MEDIA_SELECT_IMAGE:
                    if (data != null) {
                        imagePath = data.getStringExtra(SelectImageActivity.KEY_SELECT_IMAGE_PATH);
                        List<String> list = new ArrayList<>();
                        list.add(imagePath);
                        uploadPhoto(list);
                    }
                    break;
                case REQUEST_MEDIA_SELECT_IMAGE_GALLERY:
                    if (data != null) {
                        imagePath = data.getStringExtra(SelectImageActivity.KEY_SELECT_IMAGE_PATH);
                        List<String> list = new ArrayList<>();
                        list.add(imagePath);
                        uploadPhoto(list);
                    }
                    break;
                case MAPREQUEST_CODE:
                    NearAddressBean bean = (NearAddressBean) data.getSerializableExtra("address_bean");
                    if (bean != null) {
                        String address = bean.getProvince() + bean.getCity() + bean.getCounty();
                        area = bean.getCounty();
                        city = bean.getCity();
                        detailedAddress = bean.getAddress();
                        province = bean.getProvince();
                        latitudeLongitude = bean.getxOffset() + ":" + bean.getyOffset();
                        mLocationAddress.setVisibility(View.VISIBLE);
                        mLocationAddress.setText(address);
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp.setMargins(0, ConvertUtils.dip2px(getActivity(), 5), 0, 0);
                        mLocationDetialAddress.setLayoutParams(lp);
                        mLocationDetialAddress.setText(bean.getAddress());
                    }
                    break;
                case REQUEST_UPLOAD_IMAGE_CAMERA:
                    if (mFile != null) {
                        Intent intent = new Intent(getActivity(), ClipImageActivity.class);
                        intent.putExtra("key_select_image_path", mFile.getAbsolutePath());
                        startActivityForResult(intent, REQUEST_UPLOAD_IMAGE_GALLERY);
                    }
                    break;
                case REQUEST_UPLOAD_IMAGE_GALLERY:
                    if (data != null) {
                        imagePath = data.getStringExtra("key_select_image_path");
                        List<String> list = new ArrayList<>();
                        list.add(imagePath);
                        uploadPhoto(list);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void uploadPhoto(List<String> list) {
        showProgressDialog(getString(R.string.upload_pic));
        NoHttpUtils.httpUploadFileRequest(Constant.URL_UPLOADS_AVATAR, list, new NoHttpUtils.OnFileUploadListener() {
            @Override
            public void onStart(int position) {
            }

            @Override
            public void onCancel(int position) {
            }

            @Override
            public void onProgress(int position, int progress) {
            }

            @Override
            public void onFinish(int position) {
            }

            @Override
            public void onError(int position, Exception exception) {
            }
        }, new NoHttpUtils.OnFileUploadResultListener() {
            @Override
            public void onSucceed(int what, FileUploadBean fileUploadBean) {
                if ("0".equals(fileUploadBean.getCode())) {
                    if (fileUploadBean.getData() != null & fileUploadBean.getData().size() > 0) {
                        uploadUrl = fileUploadBean.getData().get(0).getPath();
                        if (!TextUtils.isEmpty(imagePath)) {
                            if (phoneFlag == 1) {
                                businessUnitIcon = uploadUrl;
                                mImgLogo.setImageBitmap(BitmapFactory.decodeFile(imagePath));
                            } else if (phoneFlag == 2) {
                                businessLicense = uploadUrl;
                                mLlUploadLincense.setVisibility(View.GONE);
                                mImgUploadLincense.setVisibility(View.VISIBLE);
                                mImgUploadLincense.setImageBitmap(BitmapFactory.decodeFile(imagePath));
                            } else if (phoneFlag == 3) {
                                businessLicense = uploadUrl;
                                mLlUploadLincense.setVisibility(View.GONE);
                                mImgUploadLincense.setVisibility(View.VISIBLE);
                                mImgUploadLincense.setImageBitmap(BitmapFactory.decodeFile(imagePath));
                            }
                        }
                    }

                } else {
                    toast(fileUploadBean.getMsg());
                }
                dismissProgressDialog();

            }

            @Override
            public void onFailed(int what, FileUploadBean fileUploadBean) {
                ToastUtils.showToast(getString(R.string.upload_pic_fail));
                dismissProgressDialog();
            }
        });
    }


    @Override
    public void getChildView(int i, View view) {
        Button take = (Button) view.findViewById(R.id.btn_take_photo);
        Button gallery = (Button) view.findViewById(R.id.btn_gallery);
        Button cancel = (Button) view.findViewById(R.id.btn_cancel);

        take.setOnClickListener(this);
        gallery.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> permissionList) {
        //当requestCode相同时候，permissions.size == 请求的权限数时候，认为权限请求成功
        if (requestCode == 1 && permissionList.size() == camreaPermission.length) {
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            // 根据文件地址创建文件
            mFile = mFileUtils.getImagesFile("IMG_" + DateUtil.formatDate(System.currentTimeMillis(), "yyyyMMdd_HHmmss") + ".jpg");

            Uri uri;

            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + BuildConfig.ProviderSuffix, mFile);
            } else {
                // 把文件地址转换成Uri格式
                uri = Uri.fromFile(mFile);
            }

            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE_CAMERA);
        } else if (requestCode == 2 && permissionList.size() == takePhonePermission.length) {
            Intent intent = new Intent(getActivity(), SelectImageActivity.class);
            if (phoneFlag == 1) {
                intent.putExtra(SelectImageActivity.KEY_SELECT_IMAGE_CLIP, true);
                startActivityForResult(intent, REQUEST_MEDIA_SELECT_IMAGE);
            } else if (phoneFlag == 2) {
                intent.putExtra(SelectImageActivity.KEY_SELECT_IMAGE_CLIP, true);
                startActivityForResult(intent, REQUEST_MEDIA_SELECT_IMAGE_GALLERY);
            }

        }
    }

    @Override
    public void onPermissionsDenied(int i, List<String> list) {
        //调用了一次拒绝权限认为失败
        PermissionUtils.permissionDialog(getActivity(), list, null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
